package com.dou.you.che.service.schedule;

import com.dou.you.che.service.sys.SysScheduleJobLogServiceI;
import com.dou.you.che.core.entity.sys.SysScheduleJob;
import com.dou.you.che.core.entity.sys.SysScheduleJobLog;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 执行的定时任务
 * @Author 黄国刚【1058118328@qq.com】
 */
public class ScheduleJob extends QuartzJobBean {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private ExecutorService service = Executors.newSingleThreadExecutor();
    @Autowired
    private SysScheduleJobLogServiceI scheduleJobLogService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        SysScheduleJob scheduleJob = (SysScheduleJob) context.getMergedJobDataMap().get(SysScheduleJob.JOB_PARAM_KEY);

        //获取spring bean
//        SysScheduleJobLogServiceI scheduleJobLogService = (SysScheduleJobLogServiceI) SpringContextUtils.getBean("sysScheduleJobLogService");

        //数据库保存执行记录
        SysScheduleJobLog log = new SysScheduleJobLog();
        log.setJobId(scheduleJob.getJobId());
        log.setBeanName(scheduleJob.getBeanName());
        log.setMethodName(scheduleJob.getMethodName());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(new Date());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(),
                    scheduleJob.getMethodName(), scheduleJob.getParams());
            Future<?> future = service.submit(task);

            future.get();

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times);
            //任务状态    0：成功    1：失败
            log.setStatus(0);

        } catch (Exception e) {

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times);

            //任务状态    0：成功    1：失败
            log.setStatus(1);
            log.setError(StringUtils.substring(e.toString(), 0, 2000));
        } finally {
            scheduleJobLogService.save(log);
        }
    }
}
